<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 左侧角色列表 -->
      <el-col :span="10">
        <el-collapse-transition>
          <el-card v-show="isFilterVisible" class="search-wrapper">
            <el-form :inline="true" :model="roleListParams">
              <el-form-item label="角色名称">
                <el-input
                  v-model="roleListParams.name"
                  clearable
                  placeholder="请输入角色名称"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-collapse-transition>
        <el-card class="box-card">
          <!-- 搜索区域 -->
          <div class="table-operations">
            <el-button
              type="primary"
              size="small"
              class="filter-trigger"
              @click="isFilterVisible = !isFilterVisible"
            >{{ isFilterVisible ? "收起" : "检索" }}
              <i
                :class="[
                  'el-icon-arrow-down',
                  { 'is-reverse': isFilterVisible },
                ]"
              />
            </el-button>
            <el-button
              type="success"
              size="small"
              icon="el-icon-plus"
              @click="handleAddRole"
            >新增角色</el-button>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handleEditRole"
            >编辑角色</el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="handleDeleteRole"
            >删除角色</el-button>
          </div>
          <el-table
            :data="roleList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="isDelete" label="是否可删除">
              <template slot-scope="scope">
                <el-tag
                  v-if="scope.row.isDelete === 1"
                  type="success"
                >是</el-tag>
                <el-tag v-else type="danger">否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="handleSetPermission(scope.row)"
                >去设置</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              background
              :current-page="roleListParams.page"
              :page-sizes="[10, 20, 30, 40, 50]"
              :page-size="roleListParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 右侧权限设置 -->
      <el-col :span="14">
        <el-card class="box-card">
          <div slot="header">
            <span>{{ currentRole.name || "请选择角色" }}</span>
          </div>

          <el-table
            ref="menuTable"
            :data="menuList"
            style="width: 100%"
            row-key="id"
            @row-click="handleRowClick"
          >
            <el-table-column label="菜单名称" min-width="180">
              <template slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="权限" width="120">
              <template slot-scope="scope">
                <div class="right-aligned-checkbox">
                  <el-checkbox
                    v-if="
                      scope.row.name !== '首页' &&
                        (!scope.row.list || scope.row.list.length === 0)
                    "
                    v-model="scope.row.status"
                    :true-label="1"
                    :false-label="0"
                    @change="() => handleCheckboxChange(scope.row)"
                  >显示</el-checkbox>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div
                  v-if="scope.row.list && scope.row.list.length"
                  class="sub-menu-list"
                >
                  <el-table
                    ref="nestedTable"
                    :data="scope.row.list"
                    style="width: 100%"
                    row-key="id"
                    :show-header="false"
                    @row-click="handleNestedRowClick"
                  >
                    <el-table-column min-width="180">
                      <template slot-scope="innerScope">
                        <div class="menu-name-cell third-level">
                          <span>{{ innerScope.row.name }}</span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column width="120">
                      <template slot-scope="innerScope">
                        <div class="right-aligned-checkbox">
                          <el-checkbox
                            v-if="
                              !innerScope.row.list ||
                                innerScope.row.list.length === 0
                            "
                            v-model="innerScope.row.status"
                            :true-label="1"
                            :false-label="0"
                            @change="() => handleCheckboxChange(innerScope.row)"
                          >显示</el-checkbox>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column type="expand">
                      <template slot-scope="innerScope">
                        <div
                          v-if="
                            innerScope.row.list && innerScope.row.list.length
                          "
                          class="sub-menu-list"
                        >
                          <el-table
                            :data="innerScope.row.list"
                            style="width: 100%"
                            row-key="id"
                            :show-header="false"
                          >
                            <el-table-column min-width="180">
                              <template slot-scope="thirdScope">
                                <div class="menu-name-cell fourth-level">
                                  <span>{{ thirdScope.row.name }}</span>
                                </div>
                              </template>
                            </el-table-column>
                            <el-table-column width="120">
                              <template slot-scope="thirdScope">
                                <div class="right-aligned-checkbox">
                                  <el-checkbox
                                    v-model="thirdScope.row.status"
                                    :true-label="1"
                                    :false-label="0"
                                    @change="
                                      () => handleCheckboxChange(thirdScope.row)
                                    "
                                  >显示</el-checkbox>
                                </div>
                              </template>
                            </el-table-column>
                          </el-table>
                        </div>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增角色对话框 -->
    <el-dialog
      :title="roleForm.id ? '编辑角色' : '新增角色'"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
          />
        </el-form-item>
        <el-form-item label="是否可删除" prop="isDelete">
          <el-radio-group v-model="roleForm.isDelete">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="roleForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selRoleListApi,
  addRoleApi,
  delRoleByIdsApi,
  selRoleByIdApi,
  updateRoleByIdApi,
  addRoleMenuApi,
  delRoleMenuByIdApi,
  selRoleMenuListByRoleIdApi
} from '@/api/system'
export default {
  name: 'RolePermission',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      },
      // 角色列表
      roleList: [],
      // 总条数
      total: 0,
      // 当前选中的角色
      currentRole: {},
      // 权限树数据
      permissionList: [
        {
          id: '1',
          label: '首页-1',
          show: true
        },
        {
          id: '100',
          label: '系统管理-100',
          children: [
            {
              id: '100-1',
              label: '用户管理-100',
              show: false,
              add: true,
              edit: true,
              delete: true,
              save: true,
              search: true,
              export: true
            },
            {
              id: '110',
              label: '角色管理-110',
              show: false,
              add: true,
              edit: true,
              delete: true,
              save: true,
              search: true,
              export: true
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isFilterVisible: false,
      // 角色列表参数
      roleListParams: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      currentRoleId: '', // 当前选中的角色id
      menuList: [], // 菜单列表
      // 新增对话框可见性
      dialogVisible: false,

      // 角色表单数据
      roleForm: {
        id: '', // id存在表示编辑，不存在表示新增
        name: '',
        isDelete: 1,
        remark: ''
      },

      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { max: 50, message: '角色名称不能超过50个字符', trigger: 'blur' }
        ],
        number: [{ required: true, message: '请输入编号', trigger: 'blur' }]
      },

      // 新增的 selectedIds 和 currentRole 属性
      selectedIds: []
    }
  },
  created() {
    this.selRoleList()
  },
  methods: {
    // 获取角色列表
    async selRoleList() {
      const res = await selRoleListApi(this.roleListParams)
      this.roleList = res.records
      this.total = res.total
    },
    // 查询
    handleQuery() {
      this.roleListParams.page = 1
      this.selRoleList()
    },
    // 重置
    resetQuery() {
      this.roleListParams = {
        page: 1,
        pageSize: 10,
        name: ''
      }
      this.selRoleList()
    },

    // 选择角色
    handleSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id)
      this.currentRole = selection.length > 0 ? selection[0] : {}
    },
    // 设置权限
    async handleSetPermission(row) {
      this.currentRole = row
      this.currentRoleId = row.id
      const res = await selRoleMenuListByRoleIdApi(row.id)
      if (res.code === 1) {
        // 递归初始化菜单数据，处理null的list和添加isExpand属性
        this.menuList = this.initMenuExpand(res.data)
      }
    },
    // 递归初始化菜单数据的方法
    initMenuExpand(menuItems) {
      if (!menuItems) return []

      return menuItems.map((item) => {
        // 创建新对象，避免修改原始数据
        const newItem = { ...item }

        // 将null的list转换为空数组
        newItem.list = newItem.list || []

        // 添加isExpand属性
        newItem.isExpand = false

        // 递归处理子菜单
        if (newItem.list.length > 0) {
          newItem.list = this.initMenuExpand(newItem.list)
        }

        return newItem
      })
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.roleListParams.pageSize = val
      this.selRoleList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.roleListParams.page = val
      this.selRoleList()
    },
    // checkbox变化
    async handleCheckboxChange(row) {
      console.log(row)
      try {
        if (row.status === 1) {
          const res = await addRoleMenuApi({
            roleId: this.currentRole.id,
            menuId: row.id
          })
          console.log(res)
          if (res.code === 1) {
            // const res = await selRoleMenuListByRoleIdApi(this.currentRoleId);
            // this.menuList = res.data;
            this.$message.success('设置成功')
          } else {
            this.$message.error(res.msg)
          }
        } else {
          const res1 = await delRoleMenuByIdApi({
            roleId: this.currentRole.id,
            menuId: row.id
          })
          if (res1.code === 1) {
            // const res = await selRoleMenuListByRoleIdApi(this.currentRoleId);
            // this.menuList = res.data;
            this.$message.success('设置成功')
          } else {
            this.$message.error(res1.msg)
          }
        }
      } catch (error) {
        this.$message.error('设置失败')
      }
    },
    // 打开新增角色对话框
    handleAddRole() {
      this.resetForm() // 重置表单，确保id为空
      this.dialogVisible = true
    },

    // 打开编辑角色对话框
    async handleEditRole() {
      // 检查是否有选中项
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要编辑的角色')
        return
      }

      // 只能编辑一个角色
      if (this.selectedIds.length > 1) {
        this.$message.warning('一次只能编辑一个角色')
        return
      }

      try {
        // 获取选中角色的ID
        const id = this.selectedIds[0]
        // 获取角色详情
        const res = await selRoleByIdApi(id)

        if (res.code === 1 && res.data) {
          // 根据接口返回的完整字段，填充表单数据
          this.roleForm = {
            id: res.data.id,
            name: res.data.name,
            number: res.data.number,
            isDelete: res.data.isDelete,
            remark: res.data.remark || ''
            // 不需要在表单中显示的字段可以不添加到roleForm中
            // createTime: res.data.createTime,
            // updateTime: res.data.updateTime
          }

          this.dialogVisible = true
        } else {
          this.$message.error(res.msg || '获取角色信息失败')
        }
      } catch (error) {
        console.error('获取角色信息失败:', error)
        this.$message.error('获取角色信息失败')
      }
    },

    // 重置表单
    resetForm() {
      this.$refs.roleForm && this.$refs.roleForm.resetFields()
      this.roleForm = {
        id: '', // 清空id，表示新增模式
        name: '',
        isDelete: 1,
        remark: ''
      }
    },

    // 提交表单 - 根据id区分新增和编辑
    submitForm() {
      this.$refs.roleForm.validate(async(valid) => {
        if (!valid) {
          return false
        }

        try {
          let res

          if (!this.roleForm.id) {
            // 无id，执行新增
            res = await addRoleApi(this.roleForm)
          } else {
            // 有id，执行编辑
            res = await updateRoleByIdApi(this.roleForm)
          }

          if (res.code === 1) {
            this.$message.success(
              this.roleForm.id ? '编辑角色成功' : '新增角色成功'
            )
            this.dialogVisible = false
            // 刷新角色列表
            this.selRoleList()
          } else {
            this.$message.error(
              res.msg || (this.roleForm.id ? '编辑角色失败' : '新增角色失败')
            )
          }
        } catch (error) {
          console.error(
            this.roleForm.id ? '编辑角色失败:' : '新增角色失败:',
            error
          )
          this.$message.error(
            this.roleForm.id
              ? '编辑角色失败，请稍后重试'
              : '新增角色失败，请稍后重试'
          )
        }
      })
    },

    // 处理删除角色
    handleDeleteRole() {
      // 检查是否有选中项
      if (this.selectedIds && this.selectedIds.length === 0) {
        this.$message.warning('请选择要删除的角色')
        return
      }

      this.$confirm(
        `确认删除选中的 ${this.selectedIds.length} 个角色吗？删除后不可恢复！`,
        '警告',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          try {
            // 根据接口文档，需要传入一个id数组
            const res = await delRoleByIdsApi(this.selectedIds)

            if (res.code === 1) {
              // 检查返回的数据中是否包含"无法删除选项"的提示
              if (res.data && res.data.includes('无法删除选项')) {
                // 部分删除成功，部分无法删除的情况
                this.$message({
                  type: 'error',
                  message: res.data,
                  duration: 3000
                })
              } else {
                // 全部删除成功的情况
                this.$message.success(res.data || '删除成功')
              }

              // 重置选中项
              this.selectedIds = []
              // 刷新角色列表
              this.selRoleList()
            } else {
              // API返回失败
              this.$message.error(res.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除角色失败:', error)
            this.$message.error('删除角色失败，请稍后重试')
          }
        })
        .catch(() => {
          // 用户取消删除，不做任何操作
        })
    },

    // 添加行点击展开方法
    handleRowClick(row, column, event) {
      // 只在点击有子菜单的行时触发展开/折叠
      if (row.list && row.list.length > 0) {
        this.$refs.menuTable.toggleRowExpansion(row)
      }
    },
    // 嵌套表格行点击展开
    handleNestedRowClick(row, column, event) {
      // 只在点击有子菜单的行时触发展开/折叠
      if (row.list && row.list.length > 0) {
        this.$refs.nestedTable.toggleRowExpansion(row)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* .demo-form-inline {
  display: flex;
  justify-content: space-between;
} */

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.permission-options {
  display: flex;
  gap: 15px;
}

.permission-options .el-checkbox {
  margin-right: 0;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 8px 0;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 120px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 33.33%;
}

.menu-permissions {
  padding: 20px;
}

.menu-title {
  font-weight: bold;
  margin-bottom: 15px;
}

.permission-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.permission-item {
  display: flex;
  align-items: center;
  width: calc(33.33% - 14px);
  min-width: 200px;
}

.permission-name {
  margin-right: 10px;
  color: #606266;
}

.permission-checkbox {
  margin-left: auto;
}

.menu-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 60px;
  border-bottom: 1px solid #ebeef5;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-name {
  color: #606266;
}

.sub-menu-list {
  width: 100%;
}

.sub-menu-item {
  width: 100%;
}

.menu-row {
  display: flex;
  width: 100%;
  border-bottom: 1px solid #ebeef5;
  padding: 10px 0;
}

.menu-column {
  flex: 1;
  text-align: left;
  padding-left: 20px;
}

.permission-column {
  width: 120px;
  text-align: center;
}

.menu-name {
  display: flex;
  align-items: center;
}

.menu-name.third-level {
  padding-left: 20px;
}

.third-level-menu {
  width: 100%;
}

.el-icon-arrow-right {
  margin-right: 5px;
  transition: transform 0.3s;
}

.el-icon-arrow-right.is-expand {
  transform: rotate(90deg);
}

/* 调整展开图标的位置 */
.el-table__expand-icon {
  display: none;
}

.menu-name-cell {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.menu-name-cell .el-icon-arrow-right {
  margin-right: 8px;
  transition: transform 0.3s;
}

.menu-name-cell .el-icon-arrow-right.is-expand {
  transform: rotate(90deg);
}

/* 隐藏表格默认的展开图标列 */
.el-table__expand-column {
  display: none;
}

/* 移除展开行的默认内边距 */
.el-table__expanded-cell {
  padding: 0 !important;
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.dialog-footer {
  text-align: right;
}

.menu-name.third-level {
  padding-left: 20px;
}

.menu-name.fourth-level {
  padding-left: 40px;
}

.fourth-level-menu {
  width: 100%;
  padding-left: 20px;
}

/* 设置复选框右对齐 */
.right-aligned-checkbox {
  display: flex;
  justify-content: flex-end;
  padding-right: 16px;
}

/* 确保复选框组件内部对齐 */
:deep(.el-checkbox) {
  margin-right: 0;
}

/* 确保嵌套表格线条铺满 */
:deep(.el-table__expanded-cell) {
  padding: 0 !important; /* 移除内边距 */
}

:deep(.sub-menu-list) {
  width: 100%;
}

:deep(.sub-menu-list .el-table) {
  width: 100% !important;
  margin: 0 !important;
}

/* 确保内部表格行与外部对齐 */
:deep(.el-table__expanded-cell .el-table__row) {
  width: 100%;
}

/* 修复可能的边框重叠问题 */
:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
}
</style>
